package leetcode.part3;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class S54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int u = 0;
        int d = matrix.length - 1;
        int l = 0;
        int r = matrix[0].length - 1;

        List<Integer> res = new ArrayList<>();
        while (true) {
            for (int i = l; i <= r; i++) {
                res.add(matrix[u][i]);
            }
            if (++u > d) break;
            for (int i = u; i <= d; ++i) {
                res.add(matrix[i][r]);
            }
            if (--r < l) break;
            for (int i = r; i >= l; i--) {
                res.add(matrix[d][i]);
            }
            if (--d < u) break;
            for (int i = d; i >= u; i--) {
                res.add(matrix[i][l]);
            }
            if (++l > r) break;
        }
        return res;
    }

    @Test
    public void test() {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] matrix1 = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        System.out.println(spiralOrder(matrix));
        System.out.println(spiralOrder(matrix1));
    }
}
